package com.hashtable;


/**
 * @BelongsProject: DataStructures
 * @BelongsPackage: com.hashtable
 * @Author: 江岸
 * @CreateTime: 2021-03-02 20:37
 * @Description:
 */
public class HashTabDemo {
    public static void main(String[] args) {
        HashTab hashTab = new HashTab(8);
        hashTab.add(new EmpNode(1,"aaa"));
        hashTab.add(new EmpNode(2,"bbb"));
        hashTab.add(new EmpNode(3,"ccc"));
        hashTab.add(new EmpNode(4,"ddd"));
        hashTab.add(new EmpNode(9,"vvv"));
        //hashTab.show();
        System.out.println(hashTab.findById(4));
    }
}

class HashTab{
    private EmpLinkedList[] arr;
    private int size;

    public HashTab(int size){
        arr = new EmpLinkedList[size];
        this.size = size;
    }

    public void add(EmpNode empNode){
        //用模来求位置
        int index = hashFun(empNode.id);
        if (arr[index] == null){
            arr[index] = new EmpLinkedList();
            arr[index].add(empNode);
        }else {
            arr[index].add(empNode);
        }
    }

    public EmpNode findById(int id){
        int i = hashFun(id);
        if (arr[i]==null){
            return null;
        }
        return arr[i].findById(id);
    }

    public int hashFun(int num){
        return num%8;
    }

    public void show(){
        for (int i=0;i<size;i++){
            if (arr[i] !=null){
                arr[i].show();
            }
            System.out.println();
        }
    }
}

class EmpNode{
    public int id;
    public String name;
    public EmpNode next;

    public EmpNode(int id,String name){
        this.id = id;
        this.name = name;
    }

    public EmpNode(){

    }

    @Override
    public String toString() {
        return "EmpNode{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

class EmpLinkedList{
    private EmpNode head;

    public EmpLinkedList(){

    }

    public void add(EmpNode node){
        if (head==null){
            head = node;
        }else {
            EmpNode temp = head;
            while (temp.next!=null){
                temp = temp.next;
            }
            temp.next = node;
        }
    }

    public EmpNode findById(int id){
        if (head==null){
            return null;
        }
        EmpNode temp = head;
        while (temp!=null){
            if (temp.id==id){
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }

    public void show(){
        EmpNode temp = head;
        while (temp!=null){
            System.out.printf("编号:%d,姓名:%s; \t",temp.id,temp.name);
            temp = temp.next;
        }
    }
}
